let currentProduct = null;
let currentUser = null;

// DOM元素缓存
const elements = {
    productInfo: document.querySelector('.product-info'),
    productTitle: document.querySelector('.product-title'),
    productPrice: document.querySelector('.product-price'),
    productCategory: document.querySelector('.product-category'),
    productTime: document.querySelector('.product-time'),
    productDescription: document.querySelector('.product-description'),
    actionButtons: document.querySelector('.action-buttons'),
    mainImage: document.querySelector('.main-image'),
    thumbnailContainer: document.querySelector('.thumbnail-container'),
    sellerInfo: document.querySelector('.seller-info'),
    sellerAvatar: document.querySelector('.seller-avatar'),
    sellerName: document.querySelector('.seller-name'),
    sellerRating: document.querySelector('.seller-rating'),
    favoriteButton: document.querySelector('.favorite-button'),
    commentInput: document.querySelector('.comment-input'),
    commentHint: document.querySelector('.comment-hint'),
    commentList: document.querySelector('.comment-list'),
    commentsCount: document.querySelector('.comments-count'),
    productMessage: document.getElementById('product-message'),
    imageModal: document.getElementById('image-modal'),
    modalImage: document.querySelector('.modal-image')
};

// 初始化页面
document.addEventListener('DOMContentLoaded', async () => {
    await loadCurrentUser();
    await loadProductDetails();
    setupEventListeners();
});

// 设置事件监听器
function setupEventListeners() {
    // 评论输入实时验证
    elements.commentInput.addEventListener('input', validateComment);

    // 图片点击预览
    elements.mainImage.addEventListener('click', () => {
        openImageModal(elements.mainImage.src);
    });
}

// 加载当前用户信息
async function loadCurrentUser() {
    try {
        const response = await fetch('/api/user/profile');
        if (response.ok) {
            currentUser = await response.json();
        } else {
            console.error('获取用户信息失败:', response);
        }
    } catch (error) {
        console.error('获取用户信息失败:', error);
    }
}

// 加载商品详情
async function loadProductDetails() {
    showLoading();
    const productId = new URLSearchParams(window.location.search).get('id');
    if (!productId) {
        showMessage('无效的商品ID', true);
        return;
    }

    try {
        const response = await fetch(`/api/products/${productId}`);
        if (!response.ok) {
            throw new Error('获取商品详情失败');
        }
        currentProduct = await response.json();
        updateProductDisplay();
        loadComments();
    } catch (error) {
        console.error('加载商品详情失败:', error);
        showMessage('加载商品详情失败，请重试', true);
        setTimeout(loadProductDetails, 3000); // 3秒后重试
    } finally {
        hideLoading();
    }
}

// 更新商品显示
function updateProductDisplay() {
    if (!currentProduct) return;

    // 基本信息
    elements.productTitle.textContent = currentProduct.name;
    elements.productPrice.textContent = `¥${currentProduct.price.toFixed(2)}`;
    elements.productCategory.textContent = `分类: ${currentProduct.category || '未分类'}`;
    elements.productTime.textContent = `发布时间: ${formatTime(currentProduct.created_at)}`;
    elements.productDescription.textContent = currentProduct.description;

    // 图片
    updateImages(currentProduct.images);

    // 卖家信息
    updateSellerInfo(currentProduct.seller);

    // 收藏状态
    console.log(currentProduct.is_favorite)
    updateFavoriteStatus(currentProduct.is_favorite);

    // 如果是卖家，显示编辑按钮
    if (currentUser && currentUser.id === currentProduct.seller_id && document.querySelector('.edit-product-btn') === null) {
        const editBtn = document.createElement('button');
        editBtn.className = 'action-button edit-product-btn';
        editBtn.textContent = '编辑商品';
        editBtn.onclick = showEditForm;
        elements.actionButtons.appendChild(editBtn);

        // 添加图片上传按钮
        const uploadBtn = document.createElement('button');
        uploadBtn.className = 'action-button upload-image-btn';
        uploadBtn.textContent = '上传图片';
        uploadBtn.onclick = showUploadForm;
        elements.actionButtons.appendChild(uploadBtn);
    }
}

// 显示商品编辑表单
function showEditForm() {
    const form = document.createElement('form');
    form.className = 'upload-form';
    form.innerHTML = `
        <div class="form-content">
            <h3>编辑商品信息</h3>
            <div class="form-group">
                <label>商品名称</label>
                <input type="text" id="edit-name" value="${currentProduct.name}" required>
            </div>
            <div class="form-group">
                <label>商品描述</label>
                <textarea id="edit-description" required>${currentProduct.description}</textarea>
            </div>
            <div class="form-group">
                <label>商品价格</label>
                <input type="number" id="edit-price" value="${currentProduct.price}" step="0.01" required>
            </div>
            <div class="form-actions">
                <button type="button" class="btn save-btn" onclick="submitEditForm()">保存</button>
                <button type="button" class="btn cancel-btn" onclick="closeEditForm()">取消</button>
            </div>
        </div>
    `;
    elements.productInfo.appendChild(form);
}

// 提交商品编辑
async function submitEditForm() {
    const name = document.getElementById('edit-name').value.trim();
    const description = document.getElementById('edit-description').value.trim();
    const price = parseFloat(document.getElementById('edit-price').value);

    if (!name || !description || isNaN(price)) {
        showMessage('请填写完整的商品信息', true);
        return;
    }

    try {
        showLoading();
        const response = await fetch(`/api/products/${currentProduct.id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({
                name,
                description,
                price
            })
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || '更新商品失败');
        }

        currentProduct.name = name;
        currentProduct.description = description;
        currentProduct.price = price;
        updateProductDisplay();
        showMessage('商品信息更新成功', false);
    } catch (error) {
        console.error('更新商品失败:', error);
        showMessage(error.message || '更新商品失败，请重试', true);
    } finally {
        hideLoading();
    }
    document.querySelector('.upload-form').remove();
}

// 关闭编辑表单
function closeEditForm() {
    document.querySelector('.upload-form').remove();
}

// 显示图片上传表单
function showUploadForm() {
    const form = document.createElement('form');
    form.className = 'upload-form';
    form.innerHTML = `
        <div class="form-content">
            <h3>上传商品图片</h3>
            <div class="form-group">
                <label>选择图片</label>
                <input type="file" id="upload-image" accept="image/*" multiple>
            </div>
            <div class="form-actions">
                <button type="button" class="btn save-btn" onclick="submitUploadForm()">上传</button>
                <button type="button" class="btn cancel-btn" onclick="closeUploadForm()">取消</button>
            </div>
        </div>
    `;
    elements.productInfo.appendChild(form);
}

// 提交图片上传
async function submitUploadForm() {
    const fileInput = document.getElementById('upload-image');
    if (!fileInput.files || fileInput.files.length === 0) {
        showMessage('请选择至少一张图片', true);
        return;
    }

    try {
        showLoading();
        const formData = new FormData();
        for (let i = 0; i < fileInput.files.length; i++) {
            formData.append('images', fileInput.files[i]);
        }

        const response = await fetch(`/api/product/image/${currentProduct.id}`, {
            method: 'POST',
            headers: {
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: formData
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || '上传图片失败');
        }

        const data = await response.json();
        currentProduct.images = data.images;
        updateImages(currentProduct.images);
        showMessage('图片上传成功', false);
    } catch (error) {
        console.error('上传图片失败:', error);
        showMessage(error.message || '上传图片失败，请重试', true);
    } finally {
        hideLoading();
    }
    document.querySelector('.upload-form').remove();
}

// 关闭上传表单
function closeUploadForm() {
    document.querySelector('.upload-form').remove();
}

// 更新图片显示
function updateImages(images) {
    if (!images || images.length === 0) {
        elements.mainImage.src = '/images/placeholder.jpg';
        elements.thumbnailContainer.innerHTML = '';
        return;
    }

    // 主图懒加载
    lazyLoadImage(elements.mainImage, images[0]);

    // 缩略图
    elements.thumbnailContainer.innerHTML = images.map((image, index) => `
        <img src="/images/placeholder.jpg" 
             data-src="${image}" 
             alt="商品图片 ${index + 1}" 
             class="thumbnail ${index === 0 ? 'active' : ''}"
             onclick="changeMainImage('${image}', this)">
    `).join('');

    // 懒加载缩略图
    document.querySelectorAll('.thumbnail').forEach(img => {
        lazyLoadImage(img, img.dataset.src);
    });
}

// 懒加载图片
function lazyLoadImage(imgElement, src) {
    const loader = imgElement.parentElement.querySelector('.loader');
    if (loader) loader.style.display = 'block';

    const tempImg = new Image();
    tempImg.src = src;
    tempImg.onload = () => {
        imgElement.src = src;
        if (loader) loader.style.display = 'none';
    };
    tempImg.onerror = () => {
        imgElement.src = '/images/placeholder.jpg';
        if (loader) loader.style.display = 'none';
    };
}

// 切换主图
function changeMainImage(imageSrc, thumbnail) {
    lazyLoadImage(elements.mainImage, imageSrc);
    document.querySelectorAll('.thumbnail').forEach(thumb => {
        thumb.classList.remove('active');
    });
    thumbnail.classList.add('active');
}

// 更新卖家信息
function updateSellerInfo(seller) {
    if (!seller) {
        elements.sellerInfo.style.display = 'none';
        return;
    }

    elements.sellerAvatar.textContent = seller.name ? seller.name[0].toUpperCase() : '?';
    elements.sellerName.textContent = `卖家: ${seller.name || seller.email}`;
    elements.sellerRating.textContent = `信誉: ${seller.rating || '暂无'}`;
}

// 更新收藏状态
function updateFavoriteStatus(isFavorite) {
    if (isFavorite) {
        elements.favoriteButton.classList.add('active');
        elements.favoriteButton.innerHTML = '<span class="button-icon">❤</span> 取消收藏';
    } else {
        elements.favoriteButton.classList.remove('active');
        elements.favoriteButton.innerHTML = '<span class="button-icon">❤</span> 收藏';
    }
}

// 切换收藏状态
// 初始化事件监听器
function setupEventListeners() {
    // 评论输入实时验证
    elements.commentInput.addEventListener('input', validateComment);

    // 图片点击预览
    elements.mainImage.addEventListener('click', () => {
        openImageModal(elements.mainImage.src);
    });

    // 绑定收藏按钮点击事件
    elements.favoriteButton.addEventListener('click', toggleFavorite);

    // 页面加载后立即加载用户信息
    loadCurrentUser().then(() => {
        if (currentUser) {
            updateFavoriteStatus(currentProduct.is_favorite);
        }
    });
}

async function toggleFavorite() {
    if (!currentProduct || !currentUser) {
        showMessage('请先登录或商品信息未加载', true);
        return;
    }

    if (!currentUser) {
        showMessage('请先登录', true);
        return;
    }

    try {
        showLoading();
        const requestBody = {
            user_id: currentUser.id,
            product_id: currentProduct.id
        };

        const response = await fetch(`/api/products/${currentProduct.id}/favorite`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify(requestBody)
        });

        console.log('收到响应:', response);

        console.log('响应状态:', response.status);

        if (!response.ok) {
            const errorData = await response.json();
            console.error('收藏操作失败:', {
                status: response.status,
                error: errorData
            });
            throw new Error(errorData.message || `操作失败，状态码: ${response.status}`);
        }

        const result = await response.json();
        console.log('收藏操作成功，返回数据:', {
            result: result,
            newStatus: !currentProduct.is_favorite
        });

        if (result.status !== 'success') {
            throw new Error('收藏操作未成功');
        }

        currentProduct.is_favorite = !currentProduct.is_favorite;
        updateFavoriteStatus(currentProduct.is_favorite);
        showMessage(currentProduct.is_favorite ? '已收藏商品' : '已取消收藏', false);
    } catch (error) {
        console.error('收藏操作失败:', error);
        showMessage(error.message || '收藏操作失败，请重试', true);
    } finally {
        hideLoading();
    }
}

// 加载评论
async function loadComments() {
    if (!currentProduct) return;

    try {
        showLoading();
        console.log('正在加载商品评论...');
        const response = await fetch(`/api/products/${currentProduct.id}/comments`, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        });
        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || '获取评论失败');
        }
        const result = await response.json();
        if (!result.comments || !result.status === 'success') {
            throw new Error('获取评论数据格式错误');
        }
        const comments = result.comments;
        console.log('获取到的评论数据:', comments);

        // 确保评论数据格式正确
        if (!Array.isArray(comments)) {
            throw new Error('评论数据格式不正确');
        }

        // 直接更新评论显示
        elements.commentList.innerHTML = comments.map(comment => `
            <div class="comment-item" data-id="${comment.id}">
                <div class="comment-header">
                    <span class="comment-user">${comment.user?.nickname || comment.user_name || '匿名用户'}</span>
                    <span class="comment-time">${comment.created_at ? formatTime(comment.created_at) : '刚刚'}</span>
                </div>
                <div class="comment-content">${comment.content || ''}</div>
                <div class="comment-actions">
                    ${currentUser && (currentUser.id === comment.user_id || currentUser.id === currentProduct.seller_id) ? `
                    <button class="delete-comment" onclick="deleteComment(${comment.id})">删除</button>
                    ` : ''}
                    <button class="reply-comment" onclick="showReplyForm(${comment.id})">回复</button>
                </div>
            </div>
        `).join('');

        elements.commentsCount.textContent = `(${comments.length}条)`;

        if (comments.length === 0) {
            elements.commentList.innerHTML = '<div class="no-comments">暂无评论</div>';
        }
    } catch (error) {
        console.error('加载评论失败:', error);
        showMessage(error.message || '加载评论失败，请重试', true);
    } finally {
        hideLoading();
    }
}

// 显示评论回复表单
function showReplyForm(commentId) {
    const form = document.createElement('form');
    form.className = 'reply-comment-form';
    form.innerHTML = `
        <div class="form-group">
            <textarea placeholder="输入回复内容" required></textarea>
        </div>
        <div class="form-actions">
            <button type="button" onclick="submitReply(${commentId})">回复</button>
            <button type="button" onclick="closeReplyForm()">取消</button>
        </div>
    `;
    document.querySelector(`.comment-item[data-id="${commentId}"]`).appendChild(form);
}

// 提交评论回复
async function submitReply(commentId) {
    const content = document.querySelector(`.reply-comment-form textarea`).value.trim();
    if (content.length < 10) {
        showMessage('回复内容至少需要10个字符', true);
        return;
    }

    try {
        showLoading();
        const response = await fetch(`/api/products/${currentProduct.id}/comments`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({
                content,
                parent_comment_id: commentId
            })
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || '回复失败');
        }

        await loadComments();
        showMessage('回复成功', false);
    } catch (error) {
        console.error('回复失败:', error);
        showMessage(error.message || '回复失败，请重试', true);
    } finally {
        hideLoading();
    }
}

// 关闭回复表单
function closeReplyForm() {
    document.querySelector('.reply-comment-form').remove();
}

// 提交评论
async function submitComment(event) {
    event.preventDefault();

    if (!currentProduct || !currentUser) {
        showMessage('请先登录', true);
        return false;
    }

    const content = elements.commentInput.value.trim();
    if (!validateComment()) {
        showMessage('评论至少需要10个字符', true);
        return false;
    }

    try {
        showLoading();
        console.log('正在提交评论:', content);
        const response = await fetch(`/api/products/${currentProduct.id}/comments`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            },
            body: JSON.stringify({
                action: 'add_comment',
                comment: {
                    product_id: currentProduct.id,
                    user_id: currentUser.id,
                    content: content,
                    parent_comment_id: -1
                }
            })
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || '提交评论失败');
        }

        const result = await response.json();
        console.log('评论提交成功，返回数据:', result);

        if (!result.comment_id) {
            throw new Error('评论ID缺失');
        }

        elements.commentInput.value = '';
        // 强制重新加载评论
        await loadComments();
        showMessage(result.message || '评论提交成功', false);

        return true;
    } catch (error) {
        console.error('提交评论失败:', error);
        showMessage(error.message || '提交评论失败，请重试', true);
        return false;
    } finally {
        hideLoading();
    }
}

// 更新图片显示
function updateImages(images) {
    if (!images || images.length === 0) {
        elements.mainImage.src = '/images/placeholder.jpg';
        elements.thumbnailContainer.innerHTML = '';
        return;
    }

    // 主图显示
    elements.mainImage.src = images[0] || '/images/placeholder.jpg';

    // 缩略图
    elements.thumbnailContainer.innerHTML = images.map((image, index) => `
        <img src="${image || '/images/placeholder.jpg'}" 
             alt="商品图片 ${index + 1}" 
             class="thumbnail ${index === 0 ? 'active' : ''}"
             onclick="changeMainImage('${image || '/images/placeholder.jpg'}', this)">
    `).join('');
}

// 绑定评论表单提交事件
function setupEventListeners() {
    // 评论输入实时验证
    elements.commentInput.addEventListener('input', validateComment);

    // 图片点击预览
    elements.mainImage.addEventListener('click', () => {
        openImageModal(elements.mainImage.src);
    });

    // 移除重复的事件绑定，因为现在使用HTML的onsubmit属性
}

// 删除评论
async function deleteComment(commentId) {
    if (!currentProduct || !confirm('确定要删除这条评论吗？')) {
        return;
    }

    try {
        const response = await fetch(`/api/products/${currentProduct.id}/comments/${commentId}`, {
            method: 'DELETE'
        });

        if (!response.ok) {
            throw new Error('删除评论失败');
        }

        loadComments();
        showMessage('评论已删除', false);
    } catch (error) {
        console.error('删除评论失败:', error);
        showMessage('删除评论失败，请重试', true);
    }
}

// 验证评论输入
function validateComment() {
    const content = elements.commentInput.value.trim();
    const minLength = 10;
    const remaining = minLength - content.length;

    if (remaining > 0) {
        elements.commentHint.textContent = `还需输入${remaining}个字符`;
        elements.commentHint.style.color = '#ff4444';
        return false;
    } else {
        elements.commentHint.textContent = '可以发表评论了';
        elements.commentHint.style.color = '#4CAF50';
        return true;
    }
}

// 联系卖家
async function contactSeller() {
    if (!currentProduct || !currentUser) {
        showMessage('请先登录', true);
        return;
    }

    try {
        showLoading();
        const response = await fetch(`/api/user/${currentProduct.seller.id}/contact`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${localStorage.getItem('token')}`
            }
        });

        if (!response.ok) {
            const errorData = await response.json();
            throw new Error(errorData.error || '获取联系方式失败');
        }

        const data = await response.json();
        if (data.contact) {
            // 显示联系方式但不直接跳转
            const contactInfo = document.createElement('div');
            contactInfo.className = 'contact-info';
            contactInfo.innerHTML = `
                <p>卖家联系方式: ${data.contact}</p>
                <button onclick="window.location.href='mailto:${data.contact}?subject=关于商品《${currentProduct.name}》的咨询'">
                    发送邮件
                </button>
            `;
            elements.productInfo.appendChild(contactInfo);
        } else {
            showMessage('未能获取卖家联系方式', true);
        }
    } catch (error) {
        console.error('联系卖家失败:', error);
        showMessage(error.message || '联系卖家失败，请重试', true);
    } finally {
        hideLoading();
    }
}

// 打开图片预览模态框
function openImageModal(imageSrc) {
    elements.modalImage.src = imageSrc;
    elements.imageModal.style.display = 'block';
}

// 关闭模态框
function closeModal() {
    elements.imageModal.style.display = 'none';
}

// 显示加载状态
function showLoading() {
    document.querySelectorAll('.loader').forEach(loader => {
        loader.style.display = 'block';
    });
}

// 隐藏加载状态
function hideLoading() {
    document.querySelectorAll('.loader').forEach(loader => {
        loader.style.display = 'none';
    });
}

// 显示消息
function showMessage(message, isError) {
    const messageElement = elements.productMessage;
    messageElement.textContent = message;
    messageElement.style.backgroundColor = isError ? '#ff4444' : '#4CAF50';
    messageElement.style.display = 'block';

    // 添加淡出动画
    messageElement.style.opacity = '1';
    setTimeout(() => {
        messageElement.style.opacity = '0';
        setTimeout(() => {
            messageElement.style.display = 'none';
            messageElement.style.opacity = '1';
        }, 300);
    }, 3000);
}

// 格式化时间
function formatTime(timestamp) {
    const date = new Date(timestamp);
    return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}`;
}

// 补零
function padZero(num) {
    return num < 10 ? `0${num}` : num;
}
